package com.ityc.aop;

import com.ityc.pojo.OperateLog;
import com.ityc.mapper.OperateLogMapper;
import com.ityc.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 定义切点：com.ityc.controller包下的所有方法


    @Around("@annotation(com.ityc.anno.Log)")
    public Object recordOperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法执行开始时间
        long startTime = System.currentTimeMillis();
        
        // 执行目标方法并获取返回值
        Object result = joinPoint.proceed();
        
        // 计算方法执行耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        // 获取方法签名信息
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        
        // 构建操作日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentEmpId()); // 需要实现获取当前用户ID的方法
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);

        // 保存操作日志
        log.info("保存操作日志:{}",operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    // 获取当前操作人ID的方法（需要根据实际系统实现）
    private Integer getCurrentEmpId() {
        // 这里需要根据你的认证系统获取当前用户ID
        // 例如从Spring Security的SecurityContext中获取
        // 这里先返回一个模拟值
        return CurrentHolder.getCurrentId();
    }
}